
Imports System
Imports System.Collections
Imports System.Data.SqlClient
Imports _2bMatesSite.Common


Namespace _2bMatesSite.BO
	''' <summary>
	''' 2BMates bulletin message.
	''' </summary>
	Public Class BulletinMessage
		Inherits Message
		Public Sub New(ByVal dr As SqlDataReader)
			MyBase.New(dr)
		End Sub

		Public Sub New(ByVal fromUID As Integer, ByVal subject As String, ByVal body As String)
			MyBase.New(fromUID, -1, subject, body)
			senderUID = fromUID
			Me.subject = subject
			Me.body = body
		End Sub

		' Do not store bulletins in the outbox
		Public Overloads Overrides ReadOnly Property StoreInOutbox() As Boolean
			Get
				Return False
			End Get
		End Property

		Public Overloads Overrides ReadOnly Property MessageType() As Messages.MessageType
			Get
				Return Messages.MessageType.mtBulletin
			End Get
		End Property

		Public Overloads Overrides ReadOnly Property Recipients() As ArrayList
			Get
				' - Recieved bulletins do not have recipients list
				' - Sent and new (just composed) bulletins have
				'		the list of friends of the sender as recipients
				If box = Messages.BoxType.btInbox Then
					Return New ArrayList()
				Else
					Return GetRecipients()
				End If
			End Get
		End Property

		Public Overloads Overrides Sub RemoveRecipient(ByVal userID As Integer)
			Throw New MessageException("Can't remove recipients from a bulletin.")
		End Sub

		Public Overloads Overrides Sub AddRecipient(ByVal userID As Integer)
			Throw New MessageException("Can't add recipients to a bulletin.")
		End Sub

		Public Overloads Overrides Sub Send()
			If messageID >= 0 Then
				Throw New MessageException("Can't send bulletins that are already sent.")
			End If

			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()
			Dim trans As SqlTransaction = conn.BeginTransaction()

			Try
				' Send the bulletin
				Send(trans, Messages.MessageType.mtBulletin)

				' Store the bulletin in the sender's outbox
				Insert(trans, -1, DateTime.Now, Messages.BoxType.btOutbox)

				' Done
				trans.Commit()
			Catch generatedExceptionName As Exception
				trans.Rollback()
				Throw
			Finally
				conn.Close()
			End Try
		End Sub


		'
		' Private methods
		'

		' Returns an array of user ID's
		Private Function GetRecipients() As ArrayList
			Dim friends As New UsersFriends(senderUID)
			Dim res As New ArrayList()

			For Each df As DirectFriend In friends
				res.Add(df.FriendID)
			Next

			Return res
		End Function
	End Class
End Namespace






